# -*- encoding: utf-8 -*-
"""
File Name: monitor_service
Description:
Author : 'lirui'
date: 2024/7/16
Contact: marjey_lee@163.com
Change Activity:
2024/7/16:
"""

import ll
from ll import TimeFormat
from projects.monitoring.alarm_manager.services.redis_alarm_manager import RedisAlarmManager
from projects.monitoring.common.do.alarm import Alarm
from projects.monitoring.common.utils.redis_problem_publishers_manager import RedisProblemsPublishersManager
from projects.monitoring.internal_web_spider_monitor.service.monitor_pages.inspect_aliyun_env import inspect_aliyun_network
from projects.monitoring.internal_web_spider_monitor.service.monitor_pages.inspect_bofen_network import inspect_bofen_network
from projects.monitoring.internal_web_spider_monitor.service.monitor_pages.inspect_ring_network import inspect_ring_network
from projects.monitoring.internal_web_spider_monitor.service.monitor_pages.inspect_xindalou_network import inspect_xindalou_network

_MANAGER = RedisAlarmManager()


class MonitorManager:
    def __init__(self):
        self.health_check = 1
        self._inspect = [inspect_bofen_network, inspect_ring_network, inspect_xindalou_network, inspect_aliyun_network]

    def _load_problems_data(self):
        all_data = []
        try:
            for fun in self._inspect:
                ll.get_logger().info(f'start {fun}.')
                data = fun()
                all_data.extend(data)
            self._send_problems_to_redis(all_data)
            self.health_check = 1
        except Exception as e:
            ll.get_logger().error(e)
            self.health_check = 0

    def run(self):
        while True:
            # try:
            self._load_problems_data()

            # except Exception as e:
            #     ll.get_logger().error(e)
            #     self.health_check = 0
            # time.sleep(400)

    def _send_problems_to_redis(self, problems):
        """
        send problems to redis.
        Args:
            problems:

        Returns:

        """
        format_problems = self._format_problems(problems)
        RedisProblemsPublishersManager.publish(
            key='web_spider',
            content=format_problems
        )
        ll.get_logger().info('Publish problems to redis.')

    @staticmethod
    def _format_problems(problems):
        """
          latest_occur_time=latest_occur_time,
            content=content,
            device_source=device_source,
            manager_address=_manager_address
        Args:
            problems:

        Returns:
        """
        format_ = {}
        for p in problems:
            alarm = Alarm(
                timestamp=TimeFormat.datetime_to_date_stamp(p['latest_occur_time']),
                ip=f'控制器:{p["manager_address"]}',
                hostname=p['device_source'],
                severity='warning',
                alarm_type='alarm',  # 'alarm,recovery'
                alarm_info=p['content'],
                note=None,
                recovery=False,
                recovery_time=None,
                manager_ip=f'控制器:{p["manager_address"]}',
                manager_port=0,
                alarm_source=f'控制器:{p["manager_address"]}',
            )
            format_[alarm.alarm_id] = alarm.to_json()
        return format_
